﻿using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;
using Tarantino.Core.Commons.Model;
using Tarantino.Core.Commons.Services.Repositories;
using Tarantino.Samples.Core.Model;
using Tarantino.Samples.Core.Services.Repositories;

namespace Tarantino.Samples.UnitTests.Services.Repositories
{
	[TestFixture]
	public class SystemUserRepositoryTester
	{
		[Test]
		public void Validates_valid_system_user_login()
		{
			CriterionSet criteria = new CriterionSet();
			criteria.AddCriterion(new Criterion(SystemUser.EMAIL_ADDRESS, "khurwitz@hotmail.com"));
			criteria.AddCriterion(new Criterion(SystemUser.ENCRYPTED_PASSWORD, "encryptedPassword"));

			SystemUser matchingUser = new SystemUser();

			MockRepository mocks = new MockRepository();
			IPersistentObjectRepository repository = mocks.CreateMock<IPersistentObjectRepository>();

			using (mocks.Record())
			{
				Expect.Call(repository.FindFirst<SystemUser>(criteria)).Return(matchingUser);
			}

			using (mocks.Playback())
			{
				ISystemUserRepository userRepository = new SystemUserRepository(repository);
				bool isValidLogin = userRepository.IsValidLogin("khurwitz@hotmail.com", "encryptedPassword");
				
				Assert.That(isValidLogin);
			}
		}

		[Test]
		public void Does_not_validate_invalid_user_login()
		{
			CriterionSet criteria = new CriterionSet();
			criteria.AddCriterion(new Criterion(SystemUser.EMAIL_ADDRESS, "khurwitz@hotmail.com"));
			criteria.AddCriterion(new Criterion(SystemUser.ENCRYPTED_PASSWORD, "encryptedPassword"));

			MockRepository mocks = new MockRepository();
			IPersistentObjectRepository repository = mocks.CreateMock<IPersistentObjectRepository>();

			using (mocks.Record())
			{
				Expect.Call(repository.FindFirst<SystemUser>(criteria)).Return(null);
			}

			using (mocks.Playback())
			{
				ISystemUserRepository userRepository = new SystemUserRepository(repository);
				bool isValidLogin = userRepository.IsValidLogin("khurwitz@hotmail.com", "encryptedPassword");

				Assert.That(isValidLogin, Is.False);
			}
		}

		[Test]
		public void Returns_user_by_email_address()
		{
			CriterionSet criteria = new CriterionSet();
			criteria.AddCriterion(new Criterion(SystemUser.EMAIL_ADDRESS, "khurwitz@hotmail.com"));
			SystemUser matchingUser = new SystemUser();

			MockRepository mocks = new MockRepository();
			IPersistentObjectRepository repository = mocks.CreateMock<IPersistentObjectRepository>();

			using (mocks.Record())
			{
				Expect.Call(repository.FindFirst<SystemUser>(criteria)).Return(matchingUser);
			}

			using (mocks.Playback())
			{
				ISystemUserRepository userRepository = new SystemUserRepository(repository);
				ISystemUser user = userRepository.GetByEmailAddress("khurwitz@hotmail.com");

				Assert.That(user, Is.SameAs(matchingUser));
			}
		}
	}
}